const { 
  createOrder, 
  getOrders, 
  getOrder, 
  updateOrderStatus, 
  cancelOrder, 
  getUserOrders,
  handleOrderCallback,
  checkPaymentStatus
} = require('../controllers/orders');

const logger = require('../config/logger');

async function orderRoutes(fastify, options) {
  // 创建订单
  fastify.post('/orders', {
    schema: {
      description: '创建新订单',
      tags: ['订单管理'],
      body: {
        type: 'object',
        required: ['storeId', 'orderStartTime', 'orderEndTime', 'bookingMethod', 'paymentMethod'],
        properties: {
          storeId: { type: 'number', description: '店铺ID' },
          seatId: { type: 'number', description: '座位ID' },
          bookingMethod: { type: 'string', description: '预约方式：如"按天"、"按小时"等' },
          paymentMethod: { type: 'string', description: '支付方式：如"余额"、"体验券"、"qpay"等' },
          orderStartTime: { type: 'string', format: 'date-time', description: '预约开始时间' },
          orderEndTime: { type: 'string', format: 'date-time', description: '预约结束时间' },
          totalAmount: { type: 'number', description: '订单原始总金额' },
          balanceDeduction: { type: 'number', description: '余额抵扣金额' },
          voucherDiscount: { type: 'number', description: '卡券优惠金额' },
          actualAmount: { type: 'number', description: '实际支付金额' }
        }
      },
      response: {
        201: {
          type: 'object',
          description: '订单创建成功',
          properties: {
            id: { type: 'number', description: '订单ID' },
            storeId: { type: 'number', description: '店铺ID' },
            seatId: { type: 'number', description: '座位ID' },
            bookingMethod: { type: 'string', description: '预约方式' },
            paymentMethod: { type: 'string', description: '支付方式' },
            status: { type: 'string', description: '订单状态' },
            orderStartTime: { type: 'string', format: 'date-time', description: '预约开始时间' },
            orderEndTime: { type: 'string', format: 'date-time', description: '预约结束时间' },
            totalAmount: { type: 'number', description: '订单原始总金额' },
            balanceDeduction: { type: 'number', description: '余额抵扣金额' },
            voucherDiscount: { type: 'number', description: '卡券优惠金额' },
            actualAmount: { type: 'number', description: '实际支付金额' },
            createdAt: { type: 'string', format: 'date-time', description: '创建时间' },
            qpayInvoiceId: { type: 'string', description: 'QPay发票ID' },
            qrText: { type: 'string', description: '二维码文本' },
            qrImage: { type: 'string', description: '二维码图片URL' },
            paymentUrl: { type: 'string', description: '支付页面URL' },
            urls: { 
              type: 'array',
              description: '支付方式列表',
              items: {
                type: 'object',
                properties: {
                  name: { type: 'string', description: '支付方式名称' },
                  description: { type: 'string', description: '支付方式描述' },
                  logo: { type: 'string', description: '支付方式logo' },
                  link: { type: 'string', description: '支付链接' }
                }
              }
            }
          }
        },
        400: {
          type: 'object',
          description: '创建失败',
          properties: {
            error: { type: 'string', description: '错误信息' }
          }
        }
      }
    },
    preHandler: [fastify.authenticate],
    handler: createOrder
  });

  // 获取订单列表
  fastify.get('/orders', {
    schema: {
      description: '获取所有订单列表',
      tags: ['订单管理'],
      response: {
        200: {
          type: 'array',
          description: '订单列表',
          items: {
            type: 'object',
            properties: {
              id: { type: 'number', description: '订单ID' },
              storeId: { type: 'number', description: '店铺ID' },
              seatId: { type: 'number', description: '座位ID' },
              bookingMethod: { type: 'string', description: '预约方式' },
              paymentMethod: { type: 'string', description: '支付方式' },
              status: { type: 'string', description: '订单状态' },
              orderStartTime: { type: 'string', format: 'date-time', description: '预约开始时间' },
              orderEndTime: { type: 'string', format: 'date-time', description: '预约结束时间' },
              totalAmount: { type: 'number', description: '订单原始总金额' },
              balanceDeduction: { type: 'number', description: '余额抵扣金额' },
              voucherDiscount: { type: 'number', description: '卡券优惠金额' },
              actualAmount: { type: 'number', description: '实际支付金额' },
              createdAt: { type: 'string', format: 'date-time', description: '创建时间' },
              user: {
                type: 'object',
                properties: {
                  name: { type: 'string', description: '用户名称' },
                  email: { type: 'string', description: '用户邮箱' }
                }
              },
              store: { type: 'object', description: '店铺信息' },
              seat: { type: 'object', description: '座位信息' },
              payment: { type: 'object', description: '支付信息' },
              voucherUsedRecords: { 
                type: 'array',
                items: {
                  type: 'object',
                  description: '使用的卡券记录'
                }
              }
            }
          }
        }
      }
    },
    preHandler: [fastify.authenticate],
    handler: getOrders
  });

  // 获取单个订单
  fastify.get('/orders/:id', {
    schema: {
      description: '获取指定订单信息',
      tags: ['订单管理'],
      params: {
        type: 'object',
        required: ['id'],
        properties: {
          id: { type: 'string', description: '订单ID' }
        }
      },
      response: {
        200: {
          type: 'object',
          description: '订单信息',
          properties: {
            id: { type: 'number', description: '订单ID' },
            storeId: { type: 'number', description: '店铺ID' },
            seatId: { type: 'number', description: '座位ID' },
            bookingMethod: { type: 'string', description: '预约方式' },
            paymentMethod: { type: 'string', description: '支付方式' },
            status: { type: 'string', description: '订单状态' },
            orderStartTime: { type: 'string', format: 'date-time', description: '预约开始时间' },
            orderEndTime: { type: 'string', format: 'date-time', description: '预约结束时间' },
            totalAmount: { type: 'number', description: '订单原始总金额' },
            balanceDeduction: { type: 'number', description: '余额抵扣金额' },
            voucherDiscount: { type: 'number', description: '卡券优惠金额' },
            actualAmount: { type: 'number', description: '实际支付金额' },
            createdAt: { type: 'string', format: 'date-time', description: '创建时间' },
            user: {
              type: 'object',
              properties: {
                name: { type: 'string', description: '用户名称' },
                email: { type: 'string', description: '用户邮箱' }
              }
            },
            store: { type: 'object', description: '店铺信息' },
            seat: { type: 'object', description: '座位信息' },
            payment: { type: 'object', description: '支付信息' },
            voucherUsedRecords: { 
              type: 'array',
              items: {
                type: 'object',
                description: '使用的卡券记录'
              }
            }
          }
        },
        404: {
          type: 'object',
          description: '订单不存在',
          properties: {
            error: { type: 'string', description: '错误信息' }
          }
        }
      }
    },
    preHandler: [fastify.authenticate],
    handler: getOrder
  });

  // 获取用户的订单列表
  fastify.get('/users/:userId/orders', {
    schema: {
      description: '获取指定用户的订单列表',
      tags: ['订单管理'],
      params: {
        type: 'object',
        required: ['userId'],
        properties: {
          userId: { type: 'string', description: '用户ID' }
        }
      },
      response: {
        200: {
          type: 'array',
          description: '用户订单列表',
          items: {
            type: 'object',
            properties: {
              id: { type: 'number', description: '订单ID' },
              storeId: { type: 'number', description: '店铺ID' },
              seatId: { type: 'number', description: '座位ID' },
              bookingMethod: { type: 'string', description: '预约方式' },
              paymentMethod: { type: 'string', description: '支付方式' },
              status: { type: 'string', description: '订单状态' },
              orderStartTime: { type: 'string', format: 'date-time', description: '预约开始时间' },
              orderEndTime: { type: 'string', format: 'date-time', description: '预约结束时间' },
              totalAmount: { type: 'number', description: '订单原始总金额' },
              balanceDeduction: { type: 'number', description: '余额抵扣金额' },
              voucherDiscount: { type: 'number', description: '卡券优惠金额' },
              actualAmount: { type: 'number', description: '实际支付金额' },
              createdAt: { type: 'string', format: 'date-time', description: '创建时间' },
              store: { type: 'object', description: '店铺信息' },
              seat: { type: 'object', description: '座位信息' },
              payment: { type: 'object', description: '支付信息' },
              voucherUsedRecords: { 
                type: 'array',
                items: {
                  type: 'object',
                  description: '使用的卡券记录'
                }
              }
            }
          }
        },
        404: {
          type: 'object',
          description: '用户不存在',
          properties: {
            error: { type: 'string', description: '错误信息' }
          }
        }
      }
    },
    preHandler: [fastify.authenticate],
    handler: getUserOrders
  });

  // 更新订单状态
  fastify.patch('/orders/:id/status', {
    schema: {
      description: '更新订单状态',
      tags: ['订单管理'],
      params: {
        type: 'object',
        required: ['id'],
        properties: {
          id: { type: 'string', description: '订单ID' }
        }
      },
      body: {
        type: 'object',
        required: ['status'],
        properties: {
          status: { type: 'string', description: '新状态' }
        }
      },
      response: {
        200: {
          type: 'object',
          description: '更新成功',
          properties: {
            id: { type: 'number', description: '订单ID' },
            status: { type: 'string', description: '订单状态' }
          }
        },
        404: {
          type: 'object',
          description: '订单不存在',
          properties: {
            error: { type: 'string', description: '错误信息' }
          }
        }
      }
    },
    preHandler: [fastify.authenticate],
    handler: updateOrderStatus
  });

  // 取消订单
  fastify.post('/orders/:id/cancel', {
    schema: {
      description: '取消订单',
      tags: ['订单管理'],
      params: {
        type: 'object',
        required: ['id'],
        properties: {
          id: { type: 'string', description: '订单ID' }
        }
      },
      response: {
        200: {
          type: 'object',
          description: '取消成功',
          properties: {
            id: { type: 'number', description: '订单ID' },
            status: { type: 'string', description: '订单状态' }
          }
        },
        404: {
          type: 'object',
          description: '订单不存在',
          properties: {
            error: { type: 'string', description: '错误信息' }
          }
        }
      }
    },
    preHandler: [fastify.authenticate],
    handler: cancelOrder
  });

  // 订单支付回调
  fastify.get('/orders/callback', {
    schema: {
      description: '订单支付回调（由QPay回调）',
      tags: ['订单管理'],
      querystring: {
        type: 'object',
        required: ['timestamp', 'nonce', 'signature', 'orderId'],
        properties: {
          timestamp: { type: 'string', description: '时间戳' },
          nonce: { type: 'string', description: '随机数' },
          signature: { type: 'string', description: '签名' },
          orderId: { type: 'string', description: '订单ID' }
        }
      },
      response: {
        200: { type: 'string', const: 'SUCCESS', description: '回调处理成功' },
        400: { type: 'string', const: 'ERROR', description: '回调处理失败' },
        404: { type: 'string', const: 'ERROR', description: '订单不存在' },
        500: { type: 'string', const: 'ERROR', description: '处理失败' }
      }
    },
    handler: handleOrderCallback
  });

  // 查询订单支付状态
  fastify.get('/orders/:orderId/status', {
    schema: {
      description: '查询订单支付状态',
      tags: ['订单管理'],
      params: {
        type: 'object',
        required: ['orderId'],
        properties: {
          orderId: { type: 'string', description: '订单ID' }
        }
      },
      response: {
        200: {
          type: 'object',
          description: '查询成功',
          properties: {
            orderId: { type: 'number', description: '订单ID' },
            status: { type: 'string', description: '支付状态' },
            paymentId: { type: 'string', description: '支付ID' },
            totalAmount: { type: 'number', description: '订单总金额' },
            balanceDeduction: { type: 'number', description: '余额抵扣金额' },
            voucherDiscount: { type: 'number', description: '卡券优惠金额' },
            actualAmount: { type: 'number', description: '实际支付金额' },
            createdAt: { type: 'string', format: 'date-time', description: '创建时间' },
            updatedAt: { type: 'string', format: 'date-time', description: '更新时间' },
            qpayInvoiceId: { type: 'string', description: 'QPay发票ID' },
            qrText: { type: 'string', description: '二维码文本' },
            qrImage: { type: 'string', description: '二维码图片URL' },
            paymentUrl: { type: 'string', description: '支付页面URL' },
            urls: { 
              type: 'array',
              description: '支付方式列表',
              items: {
                type: 'object',
                properties: {
                  name: { type: 'string', description: '支付方式名称' },
                  description: { type: 'string', description: '支付方式描述' },
                  logo: { type: 'string', description: '支付方式logo' },
                  link: { type: 'string', description: '支付链接' }
                }
              }
            }
          }
        },
        401: {
          type: 'object',
          description: '未认证',
          properties: {
            error: { type: 'string', description: '错误信息' }
          }
        },
        404: {
          type: 'object',
          description: '订单不存在',
          properties: {
            error: { type: 'string', description: '错误信息' }
          }
        },
        500: {
          type: 'object',
          description: '查询失败',
          properties: {
            error: { type: 'string', description: '错误信息' }
          }
        }
      }
    },
    handler: checkPaymentStatus,
    preHandler: [fastify.authenticate]
  });
}

module.exports = orderRoutes;